package com.foreveross.chameleon.activity;

import com.foreveross.chameleon.model.ApplicationInfo;
import com.foreveross.chameleon.task.AppDownloadCountUpdateTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;

/**
 * @description 检测更新activity
 * @author zhouzhineng
 * 
 */
public class CheckUpdatableActivity extends Activity {

	protected AlertDialog mDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 透明activity
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().getDecorView().setBackgroundColor(Color.WHITE);
		setContentView(new View(this));

		if (mDialog != null) {
			mDialog.dismiss();
		}
		Intent i = getIntent();
		String msg = i.getStringExtra("message");
		final ApplicationInfo curApp = (ApplicationInfo) i
				.getSerializableExtra("curApp");
		final ApplicationInfo newApp = (ApplicationInfo) i
				.getSerializableExtra("newApp");
		mDialog = new AlertDialog.Builder(CheckUpdatableActivity.this)
				.setTitle("应用更新")
				.setMessage(msg)
				.setCancelable(false)
				.setPositiveButton("更新", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						//更新服务端计数
						AppDownloadCountUpdateTask updateCountTask = new AppDownloadCountUpdateTask(CheckUpdatableActivity.this, null);
						updateCountTask.exec(newApp.getBuild());
						// 启动下载activity
						Intent intent = new Intent(CheckUpdatableActivity.this,
								DownloadUpdateActivity.class);
						Bundle bundle = new Bundle();
						bundle.putSerializable(
								DownloadUpdateActivity.INTENT_CURRENT_APPLICATION,
								curApp);// 当前版本
						bundle.putSerializable(
								DownloadUpdateActivity.INTENT_NEW_APPLICATION,
								newApp);// 服务器最新版本
						intent.putExtras(bundle);
						startActivity(intent);
						finish();
					}
				})
				.setNeutralButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
					}
				}).setOnKeyListener(new OnKeyListener() {
					@Override
					public boolean onKey(DialogInterface dialog, int keyCode,
							KeyEvent event) {
						if (keyCode == KeyEvent.KEYCODE_SEARCH
								&& event.getRepeatCount() == 0) {
							return true; // Pretend we processed it
						}
						return false; // Any other keys are still processed as
										// normal
					}
				}).create();
		mDialog.show();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			if (mDialog != null && mDialog.isShowing())
				mDialog.dismiss();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
